package com.my.bigsite.common.activiti.support;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.el.ExpressionManager;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.my.bigsite.common.activiti.bpm.expr.Expr;
import com.my.bigsite.common.activiti.bpm.expr.ExprProcessor;
import com.my.bigsite.modules.act.service.Conf_User_Service;

/**
 * 默认全局任务监听器
 * @author WWY
 *
 */
public class DefaultTaskListener implements TaskListener, ExprProcessor {
    /**
	 * 
	 */
	@Autowired Conf_User_Service conf_User_Service;
	private static final long serialVersionUID = 1L;
	private static Logger logger = LoggerFactory
            .getLogger(DefaultTaskListener.class);

    public void notify(DelegateTask delegateTask) {
        String eventName = delegateTask.getEventName();
        logger.info("哈哈哈监听到任务：任务名称："+delegateTask.getName()+";任务的事件名称:"+eventName);
        logger.debug("{}", this);
        logger.debug("{} : {}", eventName, delegateTask);

        if ("create".equals(eventName)) {
            try {
                this.onCreate(delegateTask);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }

        if ("assignment".equals(eventName)) {
            try {
                this.onAssignment(delegateTask);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }

        if ("complete".equals(eventName)) {
            try {
                this.onComplete(delegateTask);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }

        if ("delete".equals(eventName)) {
            try {
                this.onDelete(delegateTask);
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }

        ((TaskEntity) delegateTask).setEventName(eventName);
    }

    /**
     * 任务创建事件 1:add的时候 如何删除流程定义里的指定办理， 同事指定assigine和多个候选人，则只有assigine有效
     * @param delegateTask
     * @throws Exception
     */
    public void onCreate(DelegateTask delegateTask) throws Exception {
    	Map<String,Object> reqMap=new HashMap<String,Object>();
    	reqMap.put("NODE_ID", delegateTask
                .getExecution().getCurrentActivityId());
       	reqMap.put("PROCINS_ID", delegateTask.getProcessDefinitionId());
    	//设置节点人员
    	List<Map<String,Object>> confUsersList = conf_User_Service.getUser(reqMap);
    	logger.info("任务onCreate方法执行获取当前节点的参与人员："+confUsersList);
        logger.debug("{}", confUsersList);
        ExpressionManager expressionManager = Context
                .getProcessEngineConfiguration().getExpressionManager();
        try {
        	for(int i=0;i<confUsersList.size();i++){
        		Map<String,Object> tempMap=confUsersList.get(i);
        		
        		   String value = expressionManager
                           .createExpression((String) tempMap.get("VALUE"))
                           .getValue(delegateTask).toString();
        		   if(0==(Integer)tempMap.get("TYPE")){
        			   delegateTask.setAssignee(value);
        		   }else if(1==(Integer)tempMap.get("TYPE")){
        			   if(value.indexOf("&&") != -1){
        				   List<String> candidateUsers=new ArrayList<String>();
        				 String [] users=  value.split("&&");
        				  for(String user:users){
        					  candidateUsers.add(user);
        				  }
        			   // List<String> candidateUsers = new Expr().evaluate(value, this);
        			    delegateTask.addCandidateUsers(candidateUsers);
        			   }else{
        				   delegateTask.setAssignee(value);
        			   }
        		   }else if(2==(Integer)tempMap.get("TYPE")){
        			   if(value.indexOf("&&") != -1){
        				   List<String> candidateUsers=new ArrayList<String>(); 
        				   String [] users=  value.split("&&");
        				   for(String user:users){
         					  candidateUsers.add(user);
         				  }
        				   delegateTask.addCandidateGroups(candidateUsers);
        			   }else{
        				   delegateTask.addCandidateGroup(value);
        			   }
        			  
        		   }
        	}
        } catch (Exception ex) {
            logger.debug(ex.getMessage(), ex);
        }
    }
    public void onAssignment(DelegateTask delegateTask) throws Exception {
    }

    public void onComplete(DelegateTask delegateTask) throws Exception {
    }

    public void onDelete(DelegateTask delegateTask) throws Exception {
    }

	@Override
	public List<String> process(List<String> left, List<String> right, String operation) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<String> process(String text) {
		// TODO Auto-generated method stub
		return null;
	}
}
